package cn.dlc.com.biz.user.controller;

import cn.dlc.com.biz.core.Constants;
import cn.dlc.com.biz.room.entity.Room;
import cn.dlc.com.biz.user.entity.User;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.dlc.com.biz.core.Constants.ROOM_USER_PREFIX;

/**
 * @Author dlc
 * @Date 2024/1/8
 * @Description TODO
 * @Version 0.0.1
 */
@RestController
@RequestMapping("user")
@Api(tags = {"用户信息"})
public class UserController {

    // todo 房间内添加人员
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation(value = "用户登录", tags = {"用户信息"})
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody User user){

        Map<String, Object> result = new HashMap<>();

        user.setId(UUID.fastUUID().toString());
        if(StringUtils.isBlank(user.getNickName())) {
            throw new RuntimeException("昵称不能为空");
        }

        List<String> userListStr = redisTemplate.opsForList().range(Constants.USER_PREFIX , 0, -1);
        if(userListStr != null && !userListStr.isEmpty()) {
            List<User> userList = userListStr.stream().map(str -> {
                return JSONObject.parseObject(str, User.class);
            }).collect(Collectors.toList());

            for (User serverUser : userList) {
                if(serverUser.getNickName().equals(user.getNickName()) && serverUser.getType().equals(user.getType())) {
                    // 存在这个人了【类型和角色都一样】
                    result.put("userInfo", user);
                    return result;
                } else if(serverUser.getNickName().equals(user.getNickName()) && !serverUser.getType().equals(user.getType())){
                    result.put("error", "用户已经存在了，请修改昵称");
                    return result;
                }
            }
        }

        String userInfo = JSONObject.toJSONString(user);
        // 当前用户添加到用户信息
        redisTemplate.opsForList().leftPush(Constants.USER_PREFIX , userInfo);
        result.put("userInfo", user);

        return result;
    }

    @ApiOperation(value = "清空所有用户", tags = {"用户信息"})
    @PostMapping("cleanAllUsers")
    public Map<String, Object> login(){

        Map<String, Object> result = new HashMap<>();

        redisTemplate.delete(Constants.USER_PREFIX );

        result.put("result", "ok");

        return result;
    }

    @ApiOperation(value = "加入房间", tags = {"用户信息"})
    @PostMapping("enter")
    public Map<String, Object> enterRoom(@RequestBody User user){

        Map<String, Object> result = new HashMap<>();

        if(user != null && "1".equals(user.getType())) {

            if(StringUtils.isBlank(user.getRoomNumber())) {
                result.put("error","房间号不能为空");
                return result;
            }

            // 获取这个房间里面的人员，判断一下，不要重复了，如果已经存在了，那么直接返回，
            List<String> userListStr = redisTemplate.opsForList().range(ROOM_USER_PREFIX + user.getRoomNumber(), 0, -1);
            if(userListStr != null && !userListStr.isEmpty()) {
                List<User> userList = userListStr.stream().map(str -> {
                    return JSONObject.parseObject(str, User.class);
                }).collect(Collectors.toList());

                for (User serverUser : userList) {
                    if(serverUser.getNickName().equals(user.getNickName()) && serverUser.getType().equals(user.getType())) {
                        // 存在这个人了【类型和角色都一样】
                        result.put("result", user);
                        return result;
                    }
                }
            }

            // 如果不存在，那么新建返回
            // 参赛选手，加入列表
            String userInfo = JSONObject.toJSONString(user);
            redisTemplate.opsForList().leftPush(ROOM_USER_PREFIX + user.getRoomNumber(), userInfo);
        }
        result.put("result", user);

        return result;
    }

    @ApiOperation(value = "参赛人员列表", tags = {"用户信息"})
    @GetMapping("list/{roomNumber}")
    public Map<String, Object> listUser(@PathVariable("roomNumber") String roomNumber){

        Map<String, Object> result = new HashMap<>();

        List<User> userList = new ArrayList<>();
        // 获取所有用户信息
        List<String> userListStr = redisTemplate.opsForList().range(ROOM_USER_PREFIX + roomNumber, 0, -1);

        if(userListStr != null && !userListStr.isEmpty()) {
            userList = userListStr.stream().map(str -> {
                return JSONObject.parseObject(str, User.class);
            }).collect(Collectors.toList());
        }
        result.put("userList", userList);

        return result;
    }



    @ApiOperation(value = "清空房间用户", tags = {"用户信息"})
    @GetMapping("clearUser/{roomNumber}")
    public Map<String, Object> clearUser(@PathVariable("roomNumber") String roomNumber){

        Map<String, Object> result = new HashMap<>();

        List<User> userList = new ArrayList<>();

        // 获取所有用户信息，直接干掉这个 key
        redisTemplate.delete(ROOM_USER_PREFIX + roomNumber);

        result.put("userList", userList);

        return result;
    }


    @ApiOperation(value = "清理指定用户", tags = {"用户信息"})
    @GetMapping("removeUser/{roomNumber}/{userId}")
    public Map<String, Object> removeUser(@PathVariable("roomNumber") String roomNumber, @PathVariable("userId") String userId){

        Map<String, Object> result = new HashMap<>();

        List<User> userList = new ArrayList<>();
        // 获取所有用户信息
        List<String> userListStr = redisTemplate.opsForList().range(ROOM_USER_PREFIX + roomNumber, 0, -1);

        if(userListStr != null && !userListStr.isEmpty()) {
            for (String userStr : userListStr) {
                if(userStr.contains(userId)) {
                    redisTemplate.opsForList().remove(ROOM_USER_PREFIX + roomNumber, 0, userStr);
                }
            }

            userListStr = redisTemplate.opsForList().range(ROOM_USER_PREFIX + roomNumber, 0, -1);
            if(userListStr != null && !userListStr.isEmpty()) {
                userList = userListStr.stream().map(str -> {
                    return JSONObject.parseObject(str, User.class);
                }).collect(Collectors.toList());
            }
        }
        result.put("userList", userList);

        return result;
    }

}
